<?php

namespace app\api\controller\mall;

use think\Db;

class Distribution extends CommonMall {
    /**
     * @param $page
     * @param $pagesize
     * @return mixed
     */
    public function orders($page = 1, $pagesize = 20) {
        $rate       = 5;
        $user       = $this->member;
        $uid        = $user['id'];
        $uid_o      = $this->member_relang['id'];
        $data       = $this->db->name('mall_distribution')->where(['one_uid|two_uid|three_uid' => $uid_o])->page($page)->limit($pagesize)->select();
        $status     = ['已失效', '待结算', '已结算'];
        $users      = $this->db->name('user')
                        ->alias('u')
                        ->join('user_channel_profile cp', 'u.id=cp.user_id and sys_channel='.getenv('APP_CHANNEL'), 'left')
                        ->where(['u.id' => ['in', array_column($data, 'user_id')]])->cache(60)->column('COALESCE(cp.name, u.name) as name,COALESCE(cp.head_portrait, u.head_portrait) as head_portrait', 'u.id');
        $orders     = $this->db->name('mall_order_item')->where(['order_id' => ['in', array_column($data, 'order_id')]])->field('order_id,goods_id,num,price,sku')->select();
        $goods      = $this->db->name('mall_goods')->where(['id' => ['in', array_column($orders, 'goods_id')]])->column('image,name', 'id');
        $orderGroup = [];
        foreach ($orders as $key => $value) {
            $value['good_name']  = '';
            $value['good_image'] = '';
            if (isset($goods[$value['goods_id']])) {
                $value['good_name']  = $goods[$value['goods_id']]['name'];
                $value['good_image'] = $goods[$value['goods_id']]['image'];
            }
            if (!isset($orderGroup[$value['order_id']])) {
                $orderGroup[$value['order_id']] = [];
            }
            $orderGroup[$value['order_id']][] = $value;
        }
        foreach ($data as &$value) {
            if ($value['one_uid'] == $uid_o) {
                $value['uid']        = $value['one_uid'];
                $value['rate']       = $value['one_rate'];
                $value['commission'] = $value['one_commission'];
                $value['level']      = '一级';
            } elseif ($value['two_uid'] == $uid_o) {
                $value['uid']        = $value['two_uid'];
                $value['rate']       = $value['two_rate'];
                $value['commission'] = $value['two_commission'];
                $value['level']      = '二级';
            } else {
                $value['uid']        = $value['three_uid'];
                $value['rate']       = $value['three_rate'];
                $value['commission'] = $value['three_commission'];
                $value['level']      = '三级';
            }
            unset($value['one_uid'], $value['one_rate'], $value['one_commission'], $value['two_uid'], $value['two_rate'], $value['two_commission'], $value['three_uid'], $value['three_rate'], $value['three_commission']);
            $value['totalpricetoRMB'] = $value['totalprice'] / $rate;
            $value['commissiontoRMB'] = $value['commission'] / $rate;
            $value['status_desc']     = $status[$value['status'] + 1];
            $value['create_time']     = date('Y-m-d H:i', $value['create_time']);
            $value['update_time']     = date('Y-m-d H:i', $value['update_time']);
            $value['user']            = $users[$value['user_id']] ?? false;
            $value['order_data']      = $orderGroup[$value['order_id']] ?? false;
        }
        return $this->pass($data);
    }

    /**
     * @return mixed
     */
    public function statistics() {
        $uid     = $this->member_relang['id'];
        $one     = $this->db->name('mall_distribution')->where(['one_uid' => $uid, 'status' => 1])->sum('one_commission');
        $two     = $this->db->name('mall_distribution')->where(['two_uid' => $uid, 'status' => 1])->sum('two_commission');
        $three   = $this->db->name('mall_distribution')->where(['three_uid' => $uid, 'status' => 1])->sum('three_commission');
        $one_0   = $this->db->name('mall_distribution')->where(['one_uid' => $uid, 'status' => 0])->sum('one_commission');
        $two_0   = $this->db->name('mall_distribution')->where(['two_uid' => $uid, 'status' => 0])->sum('two_commission');
        $three_0 = $this->db->name('mall_distribution')->where(['three_uid' => $uid, 'status' => 0])->sum('three_commission');


        $child_ids = $this->db->name('mall_distribution')->where(['one_uid|two_uid|three_uid' => $uid, 'status' => 1])->column('user_id');
        $child_ids = array_unique($child_ids);
        $orders    = $this->db->name('mall_distribution')->where(['one_uid|two_uid|three_uid' => $uid])->count();

        return $this->pass([
            'level_1_commission_0' => $one_0,
            'level_2_commission_0' => $two_0,
            'level_3_commission_0' => $three_0,
            'level_1_commission_1' => $one,
            'level_2_commission_1' => $two,
            'level_3_commission_1' => $three,
            'total_commission_0'   => $one_0 + $two_0 + $three_0,
            'total_commission_1'   => $one + $two + $three,
            'child_count'          => sizeof($child_ids),
            'order_count'          => $orders
        ]);
    }

    /**
     * @param $page
     * @param $pagesize
     * @return mixed
     */
    public function toBeSettled($page = 1, $pagesize = 20) {
        $rate = 5;
        $uid  = $this->member_relang['id'];
        $data = $this->db->name('mall_distribution')
            ->where(['one_uid|two_uid|three_uid' => $uid, 'status' => 0])
            ->field('order_id,status,update_time', 'filter')
            ->page($page)
            ->limit($pagesize)
            ->order('create_time desc')
            ->select();

        foreach ($data as &$value) {
            if ($value['one_uid'] == $uid) {
                $value['uid']        = $value['one_uid'];
                $value['rate']       = $value['one_rate'];
                $value['commission'] = $value['one_commission'];
            } elseif ($value['two_uid'] == $uid) {
                $value['uid']        = $value['two_uid'];
                $value['rate']       = $value['two_rate'];
                $value['commission'] = $value['two_commission'];
            } else {
                $value['uid']        = $value['three_uid'];
                $value['rate']       = $value['three_rate'];
                $value['commission'] = $value['three_commission'];
            }
            unset($value['one_uid'], $value['one_rate'], $value['one_commission'], $value['two_uid'], $value['two_rate'], $value['two_commission'], $value['three_uid'], $value['three_rate'], $value['three_commission']);
            $value['totalpricetoRMB'] = round($value['totalprice'] / $rate, 2);
            $value['commissiontoRMB'] = round($value['commission'] / $rate, 2);
            $value['create_time']     = date('Y-m-d H:i', $value['create_time']);
        }
        return $this->pass($data);
    }

    /**
     * @param $page
     * @param $pagesize
     * @return mixed
     */
    public function teamStatistics($page = 1, $pagesize = 20) {
        $rate      = 5;
        $uid       = $this->member_relang['id'];
        // $uid       = 6;
        $child_ids = $this->db->name('mall_distribution')->where(['one_uid|two_uid|three_uid' => $uid, 'status' => 1])->page($page)->limit($pagesize)->column('user_id');
        $child_ids = array_unique($child_ids);
        $data      = Db::name('mall_distribution')
            ->where(['one_uid|two_uid|three_uid' => $uid, 'status' => 1, 'user_id' => ['in', $child_ids]])
            ->group('user_id')
            ->field('sum(one_commission) one_commission_total,sum(two_commission) two_commission_total,sum(three_commission) three_commission_total, count(id) as count, one_uid, two_uid,three_uid,user_id')->select();
        $users = $this->db->name('user')->where(['id' => ['in', $child_ids]])->column('name,head_portrait', 'id');
        foreach ($data as &$value) {
            if ($value['one_uid'] == $uid) {
                $value['commission_total'] = $value['one_commission_total'];
            } elseif ($value['two_uid'] == $uid) {
                $value['commission_total'] = $value['two_commission_total'];
            } else {
                $value['commission_total'] = $value['three_commission_total'];
            }
            unset($value['one_uid'], $value['one_commission'], $value['two_uid'], $value['two_commission'], $value['three_uid'], $value['three_commission'], $value['one_commission_total'], $value['two_commission_total'], $value['three_commission_total']);
            $value['commissionTotalToRMB'] = round($value['commission_total'] / $rate, 2);
            $value['user']                 = $users[$value['user_id']] ?? false;
        }
        return $this->pass($data);
    }
}